package com.mobile.common_library.manager;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

/**
 * author    : Urasaki
 * e-mail    : Urasaki@qq.com
 * date      : 2020/3/09 11:35
 * introduce : 屏幕管理类
 */

public class ScreenManager {
	
	private static final String TAG = "ScreenManager";
	
	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dpToPx(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}
	
	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int pxToDp(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
	
	/**
	 * 将px值转换为sp值，保证文字大小不变
	 */
	public static int pxToSp(Context context, float pxValue) {
		final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
		return (int) (pxValue / fontScale + 0.5f);
	}
	
	/**
	 * 将sp值转换为px值，保证文字大小不变
	 */
	public static int spToPx(Context context, float spValue) {
		final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
		return (int) (spValue * fontScale + 0.5f);
	}
	
	/**
	 * 拿到资源文件的dp值
	 */
	public static int getDimenDp(Context context, int dpValue) {
		return pxToDp(context, context.getResources().getDimension(dpValue));
	}
	
	/**
	 * 拿到资源文件的sp值
	 */
	public static int getDimenSp(Context context, int spValue) {
		return pxToSp(context, context.getResources().getDimension(spValue));
	}
	
	/**
	 * 获取屏幕高度(px)
	 */
	public static int getScreenHeight(Context context) {
		return context.getResources().getDisplayMetrics().heightPixels;
	}
	
	/**
	 * 获取屏幕宽度(px)
	 */
	public static int getScreenWidth(Context context) {
		return context.getResources().getDisplayMetrics().widthPixels;
	}
	
	/**
	 * 计算出来的位置，y方向就在anchorView的上面和下面对齐显示，x方向就是与屏幕右边对齐显示
	 * 如果anchorView的位置有变化，就可以适当自己额外加入偏移来修正
	 *
	 * @param anchorView  呼出window的view
	 * @param contentView window的内容布局
	 * @return window显示的左上角的xOff, yOff坐标
	 */
	public static int[] calculatePopWindowPos(final View anchorView, final View contentView) {
		final int windowPos[] = new int[2];
		final int anchorLoc[] = new int[2];
		// 获取锚点View在屏幕上的左上角坐标位置
		anchorView.getLocationOnScreen(anchorLoc);
		final int anchorHeight = anchorView.getHeight();
		// 获取屏幕的高宽
		final int screenHeight = getScreenHeight(anchorView.getContext());
		final int screenWidth = getScreenWidth(anchorView.getContext());
		contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
		// 计算contentView的高宽
		final int windowHeight = contentView.getMeasuredHeight();
		final int windowWidth = contentView.getMeasuredWidth();
		// 判断需要向上弹出还是向下弹出显示
		final boolean isNeedShowUp = (screenHeight - anchorLoc[1] - anchorHeight < windowHeight);
		if (isNeedShowUp) {
			windowPos[0] = screenWidth - windowWidth;
			windowPos[1] = anchorLoc[1] - windowHeight;
		} else {
			windowPos[0] = screenWidth - windowWidth;
			windowPos[1] = anchorLoc[1] + anchorHeight;
		}
		return windowPos;
	}
	
	/**
	 * 获取屏幕宽度(dp)
	 */
	public static int getScreenWidthDp(Context context) {
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics dm = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(dm);
		int width = dm.widthPixels;         // 屏幕宽度（像素）
		int height = dm.heightPixels;       // 屏幕高度（像素）
		float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
		int densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
		// 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
		int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
		int screenHeight = (int) (height / density);// 屏幕高度(dp)
		
		String widthStr = "屏幕宽度（像素）：" + width;
		String heightStr = "屏幕宽度（像素）：" + height;
		String dpi = "屏幕密度dpi（120 / 160 / 240）：" + densityDpi;
		String widthDpStr = "屏幕宽度（dp）：" + screenWidth;
		String heightDpStr = "屏幕高度（dp）：" + screenHeight;
		LogManager.i(TAG, "屏幕宽度（像素）：" + width);
		LogManager.i(TAG, "屏幕高度（像素）：" + height);
		LogManager.i(TAG, "屏幕密度（0.75 / 1.0 / 1.5）：" + density);
		LogManager.i(TAG, "屏幕密度dpi（120 / 160 / 240）：" + densityDpi);
		LogManager.i(TAG, "屏幕宽度（dp）：" + screenWidth);
		LogManager.i(TAG, "屏幕高度（dp）：" + screenHeight);
		
		String allStr = widthStr + "*****" + heightStr + "*****" + dpi + "*****" + widthDpStr + "*****" + heightDpStr;
		//        try {
		//            ReadAndWriteManager.writeExternal(context, "mineData.txt", allStr);
		//        } catch (IOException e) {
		//            e.printStackTrace();
		//        }
		return screenWidth;
	}
	
	private static int getInternalDimensionSize(Context context, String key) {
		int result = 0;
		try {
			int resourceId = context.getResources().getIdentifier(key, "dimen", "android");
			if (resourceId > 0) {
				result = Math.round(context.getResources().getDimensionPixelSize(resourceId) *
										Resources.getSystem().getDisplayMetrics().density /
										context.getResources().getDisplayMetrics().density);
			}
		} catch (Resources.NotFoundException ignored) {
			return 0;
		}
		return result;
	}
	
	public static int getStatusBarHeight(Context context) {
		return getInternalDimensionSize(context, "status_bar_height");
	}
	
	public static int getNavigationBarHeight(Context context) {
		boolean mInPortrait = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
		int result = 0;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			if (hasNavBar((Activity) context)) {
				String key;
				if (mInPortrait) {
					key = "navigation_bar_height";
				} else {
					key = "navigation_bar_height_landscape";
				}
				return getInternalDimensionSize(context, key);
			}
		}
		return result;
	}
	
	private static boolean hasNavBar(Activity activity) {
		//判断小米手机是否开启了全面屏,开启了，直接返回false
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			if (Settings.Global.getInt(activity.getContentResolver(), "force_fsg_nav_bar", 0) != 0) {
				return false;
			}
		}
		//其他手机根据屏幕真实高度与显示高度是否相同来判断
		WindowManager windowManager = activity.getWindowManager();
		Display d = windowManager.getDefaultDisplay();
		
		DisplayMetrics realDisplayMetrics = new DisplayMetrics();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			d.getRealMetrics(realDisplayMetrics);
		}
		
		int realHeight = realDisplayMetrics.heightPixels;
		int realWidth = realDisplayMetrics.widthPixels;
		
		DisplayMetrics displayMetrics = new DisplayMetrics();
		d.getMetrics(displayMetrics);
		
		int displayHeight = displayMetrics.heightPixels;
		int displayWidth = displayMetrics.widthPixels;
		
		return (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0;
	}
	
	public static Integer[] getWidthAndHeight(Window window) {
		if (window == null) {
			return null;
		}
		Integer[] integer = new Integer[2];
		DisplayMetrics dm = new DisplayMetrics();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			window.getWindowManager().getDefaultDisplay().getRealMetrics(dm);
		} else {
			window.getWindowManager().getDefaultDisplay().getMetrics(dm);
		}
		integer[0] = dm.widthPixels;
		integer[1] = dm.heightPixels;
		return integer;
	}
	
}
